package com.gm.corejava.book2;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-12-27
 * Time: 上午9:14
 * To change this template use File | Settings | File Templates.
 */
public class ClipTestFrame extends JFrame{
    private final int DEFAULT_WIDTH=400;
    private final int DEFAULT_HEIGHT=400;

    public ClipTestFrame(){
           setTitle("Clipborad Test");
           setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);

           final JTextArea textContent=new JTextArea();
           JScrollPane cp=new JScrollPane(textContent);

           add(cp, BorderLayout.CENTER);

            JPanel btnPanel=new JPanel();

            JButton copyBtn=new JButton("Copy");
            copyBtn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Clipboard clipboard=Toolkit.getDefaultToolkit().getSystemClipboard();

                    String text=textContent.getSelectedText();
                    if(text==null) text=textContent.getText();

                    clipboard.setContents(new StringSelection(text),null);
                }
            });

            JButton pasteBtn=new JButton("Paste");
            pasteBtn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Clipboard clipboard=Toolkit.getDefaultToolkit().getSystemClipboard();

                    DataFlavor dataFlavor=DataFlavor.stringFlavor;

                    if(clipboard.isDataFlavorAvailable(dataFlavor))
                    {
                        try{
                            String text= String.valueOf(clipboard.getData(dataFlavor));
                            textContent.replaceSelection(text);

                        }catch(Exception e1)
                        {
                            JOptionPane.showMessageDialog(ClipTestFrame.this,e1);
                        }
                    }
                }
            });

        btnPanel.add(copyBtn);
        btnPanel.add(pasteBtn);
        add(btnPanel,BorderLayout.SOUTH);
        }
}
